<?php


namespace Transparency;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Transparency\Client as TransparencyClient;
use Transparency\Errors\ResponseException;

abstract class Resource
{
    /** @var Client */
    protected $httpClient;

    protected $subversion = '';

    protected $version = TransparencyClient::DEFAULT_VERSION;

    protected $headers;


    public function useVersion($version)
    {
        $this->version = $version;
    }

    public function useHttpClient(Client $client)
    {
        $this->httpClient = $client;
    }

    /**
     * @throws \Transparency\Errors\TransparencyException
     */
    public function call($method, $action, $params = [])
    {
        $uri = trim($this->version . '/' . $this->subversion . '/' . $action, '/');
        try {
            $response = $this->httpClient->request($method, $uri, $params);
            $this->headers = $response->getHeaders();
            $data = $response?->getBody()?->getContents();
            return json_decode($data, true) ?? [];
        } catch (GuzzleException $e) {
            throw new ResponseException($e->getMessage(), $e->getCode(), $e);
        }
    }
}
